﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class Order_CancelController : UserController
    {
        public IOrdersService _orders { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        [Authorize]
        [HttpGet]
        public IActionResult Get(string order_no)
        {
            //检查用户是否登录
            Users userModel = GetUserInfo();
            if (userModel == null)
            {
                return Ok(new { status=0,msg= "用户尚未登录或已超时！" });
            }
            //检查订单是否存在
            Orders orderModel = _orders.GetModel(order_no);
            if (order_no == "" || orderModel == null)
            {
                return Ok(new { status = 0, msg = "订单号不存在或已删除！" });
            }
            //检查是否自己的订单
            if (userModel.id != orderModel.user_id)
            {
                return Ok(new { status = 0, msg = "不能取消别人的订单状态！" });
            }
            //检查订单状态
            if (orderModel.status > 1)
            {
                return Ok(new { status = 0, msg = "订单不是生成状态，不能取消！" });
            }
            bool result = _orders.UpdateField(order_no, "status=4");
            if (!result)
            {
                return Ok(new { status = 0, msg = "操作过程中发生不可遇知的错误！" });
            }
            //如果是积分换购则返还积分
            if (orderModel.point < 0)
            {
                _user_point_log.Add(orderModel.user_id, orderModel.user_name, -1 * orderModel.point, "取消订单，返还换购积分，订单号：" + orderModel.order_no, false);
            }
            return Ok(new { status = 1, msg = "取消订单成功！" });
        }
    }
}